#!/usr/bin/env bash
#-------------------------------------------------------
#	FileName	: test.sh
#	Author		：hpy
#	Date		：2025年05月30日
#	Description	：
#-------------------------------------------------------
 

function TEST_LIST() {
    test load.psm "01h 05h"
    test output.psm "01h 01h 01h"
    test star.psm "01h 02h 03h 00h 02h 01h 55h 02h"
	test and.psm  "01h 01h 5ah 50h"
	test or.psm   "01h 0fh 00h f6h"
	test xor.psm  "01h 00h f0h f5h"
	test add.psm  "02h 00h 01h 0ah 08h"
	test sub.psm  "00h ffh 03h"
	test test.psm "61h 62h 62h 61h"
	test compare.psm "61h 62h 62h 61h 62h"
	test shift.psm "feh ffh 00h 03h 03h 03h 01h 80h c0h 80h 80h"
	test input-output.psm "00h 01h 01h 66h"
	test store-fetch.psm "00h 01h 66h"
	test interrupt.psm "00h 01h"
	test jump-nojumpat.psm "00h 01h 02h 03h 04h 05h 06h 07h 08h 10h"
	test call-return-nocallat.psm "01h 02h 04h 05h ffh 61h 61h 61h 61h"
	test jump.psm "00h 01h 02h 03h 04h 05h 06h 07h 08h 10h ffh"
	test call-return.psm "01h 02h 04h 05h ffh 07h 61h 61h 61h 61h"
}


# ------------------------------------------------------------------
cd $(dirname $(realpath $0))
root_dir=$(pwd)
build_dir="$root_dir/../build"

# 定义颜色变量
GREEN='\033[0;32m'    # 绿色
RED='\033[0;31m'      # 红色
NC='\033[0m'          # 重置颜色


rm -rf $build_dir
mkdir -p $build_dir
rm -rf $build_dir/test_result.txt
rm -rf $build_dir/color_result.txt

function test() {
    cd $root_dir
    local psm=$(realpath $1) 
    # $2 转换为数组
    local expans=($2)

    cat $psm > $build_dir/test.psm


    opbasm  -6 -e 0xfff  $build_dir/test.psm -o $build_dir
    cp $build_dir/test.mem $build_dir/test.hex  && sed -i '1d' $build_dir/test.hex 

    iverilog -o ../build/tb.vvp  -y ../rtl -y . tb.v
    cd $build_dir && vvp tb.vvp
    echo "-----------------------------"

    local result=$(cat $build_dir/test.txt)
    result=($result)
    echo "result: ${result[@]}"
    echo "expans: ${expans[@]}"

    local oky=1

    # 判断个数是否相等
    if [ ${#result[@]} -ne ${#expans[@]} ] ; then
        oky=0
    fi

    if [ $oky -eq 1 ] ; then
        # 判断每个元素是否相等
        for (( i=0; i<${#result[@]}; i++ ))
        do
            if [ ${result[$i]} != ${expans[$i]} ] ; then
                oky=0
                break
            fi
        done
    fi

    local name=$(basename $psm)
    if [ $oky -eq 1 ] ; then
        echo  -e "TEST $name ${GREEN}success${NC}" 
        echo  "$name success" >> $build_dir/test_result.txt
        echo  -e "TEST $name ${GREEN}success${NC}" >> $build_dir/color_result.txt
    else
        echo  -e "TEST $name ${RED}failed${NC}"
        echo  "$name failed${NC}" >> $build_dir/test_result.txt
        echo  -e "TEST $name ${RED}failed${NC}" >> $build_dir/color_result.txt
    fi
}




TEST_LIST

echo ">>>>>>>>>> test result <<<<<<<<<<"
cat $build_dir/color_result.txt | column -t -s ' '